package edu.utexas.mapreduce;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

class HttpFileHandler implements HttpHandler {
	
	final String baseURI;
	final String baseDir;
	
	HttpFileHandler(String baseURI, String baseDir, SharedMapState sState) {
		this.baseURI = baseURI;
		this.baseDir = baseDir;
	}
	
	public void handle(HttpExchange t) throws IOException {
		
		final String uri = t.getRequestURI().toString();
		final String filename = baseDir + "/map_output" + uri.substring(baseURI.length());
		
		System.out.println("HTTP file request:");
		System.out.println("  URI: " + uri);
		System.out.println("  File: " + filename);
		
		try {
			FileInputStream fileStream = new FileInputStream(filename);
			t.sendResponseHeaders(200, fileStream.available());
			OutputStream os = t.getResponseBody();

			// copy file to request body output stream
			{
				byte[] buffer = new byte[1024];
				int bytesRead;
				while ((bytesRead = fileStream.read(buffer)) != -1)
				{
					os.write(buffer, 0, bytesRead);
				}
			}
			os.close();
		}
		catch(FileNotFoundException e) {
			System.out.println("  file not found");
			t.sendResponseHeaders(404, -1);
			// throw e;
		}
	}
}
